package com.gzhryc.shared_device.oem.h5.mng.controllers.pcl;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.device.dao.db.DeviceType;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeService;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLFeeTemplate;
import com.gzhryc.shared_device.pcl.code.dao.models.SetMealContent;
import com.gzhryc.shared_device.pcl.code.services.PCLFeeTemplateService;
import com.gzhryc.shared_device.pcl.code.services.dto.PCLFeeTemplateSearch;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

public class PCLFeeTemplateController {

    @Route(value = { "/pcl/fee_template/list.html" })
    public String list(HttpServletRequest request) {
        List<String> deviceTypeIds = DeviceTypeFuncService.self().findTypeIdByCode(EDeviceFunCode.PCL.index());
        if(deviceTypeIds != null && deviceTypeIds.size() > 0) {
            List<DeviceType> deviceTypeList = DeviceTypeService.self().findByIds(deviceTypeIds);
            request.setAttribute("deviceTypeList", deviceTypeList);
        }
        return "/pcl/cost/fee_template/list.html";
    }

    @Route(value = "/pcl/fee_template/list.data")
    public ListResult<PCLFeeTemplate> listData(HttpServletRequest request) {
        ListResult<PCLFeeTemplate> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PCLFeeTemplateSearch search = WebUtils.getParameter(request, PCLFeeTemplateSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(PCLFeeTemplateService.self().countJoinBySearch(search));
        List<PCLFeeTemplate> feeTemplateList = PCLFeeTemplateService.self().findJoinBySearch(search, pageNo, pageLimit);
        if (feeTemplateList != null && feeTemplateList.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(feeTemplateList);
        }
        return result;
    }

    @Route(value = { "/pcl/fee_template/add.html" })
    public String add(HttpServletRequest request,HttpSession session) {
        List<String> deviceTypeIds = DeviceTypeFuncService.self().findTypeIdByCode(EDeviceFunCode.PCL.index());
        if(deviceTypeIds != null && deviceTypeIds.size() > 0) {
            List<DeviceType> deviceTypeList = DeviceTypeService.self().findByIds(deviceTypeIds);
            request.setAttribute("deviceTypeList", deviceTypeList);
        }
        SetMealContent setMealContent = new SetMealContent();
        session.setAttribute(WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_0",setMealContent);
        return "/pcl/cost/fee_template/edit.html";
    }

    @Route(value = {"/pcl/fee_template/add.do"})
    public AjaxResult doAdd(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增收费模版失败");
        PCLFeeTemplate feeTemplate = WebUtils.getParameter(request, PCLFeeTemplate.class);
        SetMealContent setMealContent = WebUtils.getAttribute(session,WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_0",SetMealContent.class);
        if(setMealContent != null && setMealContent.getItems().size() > 0){
            try {
                feeTemplate.setSetMealContent(JsonTools.toJson(setMealContent));
                if (PCLFeeTemplateService.self().add(feeTemplate)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else{
            result.setMsg("请添加套餐信息");
        }
        return result;
    }

    @Route(value = { "/pcl/fee_template/update.html" })
    public String update(HttpServletRequest request,HttpSession session) {
        Long id = WebUtils.getLong(request,"id");
        PCLFeeTemplate feeTemplate = PCLFeeTemplateService.self().getJoinById(id);
        WebUtils.setAttribute(request,feeTemplate);

        if(StringTools.isNotBlank(feeTemplate.getSetMealContent())){
            SetMealContent setMealContent = JsonTools.fromJson(feeTemplate.getSetMealContent(),SetMealContent.class);
            session.setAttribute(WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + feeTemplate.getId(),setMealContent);
        }

        List<String> deviceTypeIds = DeviceTypeFuncService.self().findTypeIdByCode(EDeviceFunCode.PCL.index());
        if(deviceTypeIds != null && deviceTypeIds.size() > 0) {
            List<DeviceType> deviceTypeList = DeviceTypeService.self().findByIds(deviceTypeIds);
            request.setAttribute("deviceTypeList", deviceTypeList);
        }
        return "/pcl/cost/fee_template/edit.html";
    }

    @Route(value = {"/pcl/fee_template/update.do"})
    public AjaxResult doUpdate(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改收费模版失败");
        PCLFeeTemplate feeTemplate = WebUtils.getParameter(request, PCLFeeTemplate.class);
        SetMealContent setMealContent = WebUtils.getAttribute(session,WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + feeTemplate.getId(),SetMealContent.class);
        if(setMealContent != null && setMealContent.getItems().size() > 0) {
            try {
                if(feeTemplate.getUserId() == null){
                    feeTemplate.setUserId(0L);  //不设置则是平台模版
                }
                feeTemplate.setSetMealContent(JsonTools.toJson(setMealContent));
                if (PCLFeeTemplateService.self().updateNotNull(feeTemplate)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else{
            result.setMsg("请添加套餐信息");
        }
        return result;
    }


    @Route(value = {"/pcl/fee_template/set_def.do"})
    public AjaxResult odSetDef(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增收费模版失败");
        Long id = WebUtils.getLong(request,"id");
        if(id != null){
            try {
                if(PCLFeeTemplateService.self().setDefState(id)){
                    result.setCode(DtoConstants.SUCCESS,null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = "/pcl/fee_template/item/list.data")
    public ListResult<SetMealContent.Item> itemListData(HttpServletRequest request, HttpSession session) {
        ListResult<SetMealContent.Item> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long templateId = WebUtils.getLong(request,"templateId",0L);
        SetMealContent setMealContent = WebUtils.getAttribute(session,WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + templateId,SetMealContent.class);
        if(setMealContent != null && setMealContent.getItems() != null && setMealContent.getItems().size() > 0){
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(setMealContent.getItems());
        }
        return result;
    }

    @Route(value = { "/pcl/fee_template/item/edit.html" })
    public String addItem(HttpServletRequest request, HttpSession session) {
        Long templateId = WebUtils.getLong(request,"templateId",0L);
        Integer id = WebUtils.getInteger(request,"id");
        if(id != null){
            SetMealContent setMealContent = WebUtils.getAttribute(session,WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + templateId,SetMealContent.class);
            if(setMealContent != null && setMealContent.getItems().size() > 0){
                for(SetMealContent.Item item : setMealContent.getItems()) {
                    if (item.getId().equals(id)) {
                        WebUtils.setAttribute(request,item);
                        break;
                    }
                }
            }
        }

        return "/pcl/cost/fee_template/item.html";
    }

    @Route(value = {"/pcl/fee_template/item/save.do"})
    public AjaxResult doSaveItem(HttpServletRequest request, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增套餐失败");
        Long templateId = WebUtils.getLong(request,"templateId",0L);
        Double moneyStr = WebUtils.getDouble(request,"moneyStr");
        if(moneyStr > 20){
            result.setMsg("套餐价格不能超过20元");
            return result;
        }
        Integer hours = WebUtils.getInteger(request,"hours",0);
        if(hours <= 0){
            result.setMsg("请填写套餐的服务时长");
            return result;
        }
        SetMealContent.Item entity = WebUtils.getParameter(request, SetMealContent.Item.class);
        entity.setMoney(NumberTools.changeMoney(moneyStr));
        entity.setTimes(hours * 60);
        SetMealContent setMealContent = WebUtils.getAttribute(session,WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + templateId,SetMealContent.class);
        if(setMealContent == null){
            setMealContent = new SetMealContent();
        }

        boolean flag = true;
        for(SetMealContent.Item item : setMealContent.getItems()){
            if(item.getId().equals(entity.getId())){
                flag = false;
                item.setName(entity.getName());
                item.setMoney(entity.getMoney());
                item.setTimes(entity.getTimes());
                item.setMoney(entity.getMoney());
                break;
            }
        }

        if(flag){
            setMealContent.getItems().add(entity);
        }
        session.setAttribute(WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + templateId,setMealContent);
        result.setCode(DtoConstants.SUCCESS,null);
        return result;
    }

    @Route(value = {"/pcl/fee_template/item/del.do"})
    public AjaxResult doDelItem(HttpServletRequest request, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除套餐失败");
        Long templateId = WebUtils.getLong(request,"templateId",0L);
        Integer id = WebUtils.getInteger(request,"id");
        if(id != null){
            SetMealContent setMealContent = WebUtils.getAttribute(session,WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + templateId,SetMealContent.class);
            if(setMealContent != null && setMealContent.getItems().size() > 0){
                int index = -1;
                for(int i=0;i<setMealContent.getItems().size();i++){
                    SetMealContent.Item item = setMealContent.getItems().get(i);
                    if(item.getId().equals(id)){
                        index = i;
                        break;
                    }
                }

                if(index >= 0){
                    setMealContent.getItems().remove(index);
                    session.setAttribute(WebConstants.SESSION_PCL_SET_MEAL_CONTENT + "_" + templateId,setMealContent);
                    result.setCode(DtoConstants.SUCCESS,null);
                }
            }
        }
        return result;
    }

    @Route(value = {"/pcl/fee_template/del.do"})
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除收费模版失败");
        Long id = WebUtils.getLong(request,"id");
        Long total = PlaceBusinessConfigService.self().countByFeeTemplateId(EDeviceFunCode.PCL.index(),id);
        if(total != null && total > 0){
            result.setMsg("该收费模版正在使用，不允许删除");
            return result;
        }

        try {
            if(PCLFeeTemplateService.self().deleteById(id)){
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
